<?php

class Module_View extends Ingenii_Module {
	
	private $conn;
	private $locations = array();
	private $renderedLocations = array();
	private $template;
	
	private $template_folder;
	
	public function __construct(Doctrine_Collection $parameters) {
		parent::__construct($parameters);		
		$this->conn = Doctrine_Manager::getInstance()->getCurrentConnection();
		$this->traverseViewTree($this->parameters->id);
		
		$this->template_folder = $this->config = Ingenii_Config::getInstance()->base->modules->view->templateFolder;
	}
	
	private function traverseViewTree($id) {
		$view = ModuleView::getById($id);
		
		if($view->baseView==NULL) {
			$locations = $view->locations;
			$this->setLocations($locations);
			$this->template = $view->templateFile;
		} else {
			$this->traverseViewTree($view->baseView->id);
		}		
		$this->addResourcesToLocations($view->resources);
	}
	
	private function setLocations($locations) {
		foreach($locations as $location) {
			$this->locations[$location->name] = array();
		}
	}
	
	private function addResourcesToLocations($resources) {
		foreach($resources as $resource) {
			$location  = $resource->ResourceModuleView[0]->location->name;
			$module = Ingenii_Module::returnModule($resource->module->className, 
											       $resource->resourceParameters);
			$this->locations[$location][] = $module;
		}
	}
	
	private function renderLocations() {
		foreach($this->locations as $location => $resources) {
			foreach($resources as $resource) {
				$this->renderedLocations[$location][] = $this->renderResource($resource->parameters->id);
			}
		}
	}
	
	private function renderResource($id) {
		$resource = Resource::getById($id);
		$module = Ingenii_Module::returnModule($resource->module->className, $resource->resourceParameters);
		
		ob_start();
		$module->run();
		$output = ob_get_contents();
		ob_end_clean();
		return $output;
	}
	
	public function run() {
		$this->renderLocations();
		
		$view = new Zend_View();
		foreach($this->renderedLocations as $location => $contents) {
			$view->{$location} = $contents;
		}
		$view->setScriptPath(BASEPATH . $this->template_folder);
		echo $view->render($this->template);
	}	
}